/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.worlds.object;

import net.worlds.WorldsException;
import net.worlds.Main;
import se.krka.kahlua.vm.JavaFunction;
import se.krka.kahlua.vm.LuaCallFrame;
import se.krka.kahlua.vm.LuaClosure;


public class TaskScheduler extends GameObject{
    public TaskScheduler() throws WorldsException
    {
        super("TaskScheduler");
        explorable = false;
        addFunction("schedule", new JavaFunction()
        {

            public int call(final LuaCallFrame callFrame, int nArguments) {
                if(nArguments != 2)
                    throw new RuntimeException("schedule() requires 1 argument");
                if(!(callFrame.get(1) instanceof LuaClosure))
                    throw new RuntimeException("schedule() requires a function argument");
                final LuaClosure f = (LuaClosure)callFrame.get(1);
                Main.runInMainThread(new Runnable()
                {
                    public void run() {
                        if(callFrame.isLua())
                            synchronized(callFrame.closure.env)
                            {
                                Main.getScriptContext().call(callFrame.thread.state, f);
                            }
                        else
                            synchronized(callFrame.thread.environment)
                            {
                                Main.getScriptContext().call(callFrame.thread.state, f);
                            }
                    }
                });
                return 0;
            }

        });
        //x_;
    }
}
